<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="800px"
    append-to-body
    :close-on-click-modal="false"
    @close="closeModal"
  >
    <el-form ref="form" :model="form" :show-message="false" label-width="110px">
      <el-form-item label="处方类型">
        <dict-tag :options="dict.type.tcm_prescript_type" :value="String(templateCategory)" />
      </el-form-item>
      <el-form-item label="模板名称" prop="templateName" required>
        <el-input
          v-model.trim="form.templateName"
          placeholder="请输入模板名称"
          clearable
          :maxLength="50"
        ></el-input>
      </el-form-item>
      <!-- 省区 -->
      <el-form-item
        v-if="templateType === '1'"
        label="模板可见范围"
        prop="regionCode"
        required
      >
        <el-select
          v-model="form.regionCode"
          placeholder="请选择省份"
          clearable
          filterable
        >
          <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 院内 || 个人 -->
      <el-form-item v-else label="模板可见范围">
        <div>{{ templateType === '2' ? '院内可见' : '个人可见'}}</div>
      </el-form-item>
      <el-form-item label="模板归属" prop="ownerId" required>
        <!-- 省区选择渠道 -->
        <Treeselect
          v-if="templateType === '1'"
          ref="Treeselect"
          v-model="form.ownerId"
          :options="channelOptions"
          :show-count="true"
          placeholder="请选择模板归属渠道"
          noResultsText="暂无数据"
          @input="handChangeChannel"
        />
        <!-- 院内选择单位 -->
        <SelectCompany
          v-if="templateType === '2'"
          :defaultValue.sync="form.ownerId"
          :companyType="0"
          placeholder="请选择模板归属单位"
          style="width: 100%"
        />
        <!-- 个人选择专家 -->
        <SelectExpert
          v-if="templateType === '3'"
          :defaultValue.sync="form.ownerId"
        />
      </el-form-item>

      <el-form-item label="功效" prop="effect">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入处方功效"
          v-model="form.effect"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="主治" prop="mainTreat">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入处方主治功能"
          v-model="form.mainTreat"
        >
        </el-input>
      </el-form-item>

      <div v-for="(item, index) in form.materialsItems" :key="index" :class="{ forBox: templateCategory === 1 }">
        <div class="disFlx">
          <el-tag
            v-if="templateCategory === 1"
            type="warning"
            effect="dark"
            class="sortTag shrink0"
            >贴{{ index + 1 }}</el-tag
          >
          <div class="disFlx" style="flex: 1">
            <div class="formItemTitle shrink0">添加药材</div>
            <SearchDrug v-if="open" @change="(val) => handDrugChange(val, index)" />
          </div>
          <div v-if="templateCategory === 1" class="ml-10 shrink0">
            <el-button
              v-if="form.materialsItems.length > 1"
              type="danger"
              size="medium"
              @click="removeForBox(index)"
              >删除</el-button
            >
            <el-button type="primary" size="medium" @click="addForBox">新增贴</el-button>
          </div>
        </div>

        <el-table :data="item.materials" border class="mt-10">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="55"
          />
          <el-table-column
            label="药材名称"
            align="center"
            prop="materialsName"
          />
          <el-table-column label="剂量" align="center" width="100">
            <template slot-scope="{ row }">
              <div class="disFlxAC">
                <el-input-number
                  :controls="false"
                  :precision="templateCategory === 1 ? 2 : 0"
                  :min="0"
                  v-model="row.dose"
                  placeholder="请输入"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="计量单位" align="center" width="120">
            <template slot-scope="{ row }">
              <el-select v-model="row.unitId" placeholder="请选择">
                <el-option
                  v-for="item in unitList"
                  :key="item.unitId"
                  :label="item.unit"
                  :value="item.unitId"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template slot-scope="{ row, $index }">
              <el-button size="mini" type="text" @click="removeRow(index, $index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <div v-if="templateCategory === 1" class="mt-10">
          <el-button
            type="success"
            size="mini"
            class="mr-10"
            @click="openAcupointSelect(index)"
            >添加穴位</el-button
          >
          <el-tag
            v-for="acupoints in item.acupoints"
            :key="acupoints.id"
            class="forTag"
            type="warning"
            effect="plain">
            {{ acupoints.acupointName }}
          </el-tag>
        </div>
      </div>
    </el-form>

    <AcupointSelect ref="AcupointSelect" @change="acupointChange" />

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="loading" @click="submitForm">确 定</el-button>
      <el-button @click="open = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { treeselect } from "@/api/channel/channel";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import SelectCompany from '@/components/SelectCompany/index'
import SelectExpert from '@/views/expert/expert/selectExpert'
import SearchDrug from "@/views/saas/drug/searchDrug";
import { getSelectList } from "@/api/system/unit";
import AcupointSelect from '@/views/saas/acupoint/acupointSelect'
import { addTemplate, updateTemplate } from '@/api/template/index.js'
import { deepClone } from "@/utils";

export default {
  components: {
    Treeselect,
    SelectCompany,
    SelectExpert,
    SearchDrug,
    AcupointSelect
  },
  props: {
    // 模板类别: 0中药处方模版 1贴敷处方模版
    templateCategory: {
      type: Number,
      default: 0
    },
    // 模板类型: 1省区 2院内 3个人
    templateType: {
      type: String,
      default: '1'
    },
    // 省区地址列表
    areaList: {
      type: Array,
      default() {
        return []
      }
    }
  },
  dicts: [
    "tcm_prescript_type"
  ],
  data() {
    return {
      title: "新建模板",
      open: false,
      loading: false,
      form: {
        templateId: undefined,
        templateName: "", // 模板名称
        templateCategory: undefined,
        templateType: undefined,

        prescriptionType: undefined, // 处方类型
        type: undefined, // 1:经典方,2:协定方,3:专家自定

        regionCode: undefined, // 省份id
        regionName: undefined, // 省份名称
        ownerType: undefined, // 模板归属类型 1渠道 2单位 3个人
        ownerId: undefined, // 模板归属id

        effect: undefined, // 功效
        mainTreat: undefined, // 主治
        source: undefined, // 来源
        usages: undefined, // 用法

        materialsItems: [{
          acupoints: [], // 穴位
          materials: [], // 药材
        }] // 药材项
      },
      channelOptions: [], // 渠道树选项
      unitList: [],
      currentIndex: 0, // 当前添加的贴敷模板
    }
  },
  methods: {
    openModal(row, isCopy) {
      if(row && row.templateId){
        this.form = deepClone(row);

        if(isCopy){
          this.form.templateId = undefined;
        }else{
          this.title = '编辑模板';
        }
      }
      this.open = true;

      getSelectList({ pageNum: 1, pageSize: 999 }).then(res => {
        this.unitList = res.rows;
      })
      this.getTreeselect();

      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },
    closeModal() {
      this.loading = false;
      Object.assign(this.$data, this.$options.data());
    },
    /** 查询渠道下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.channelOptions = response.data;
      });
    },
    handChangeChannel(e) {
      this.$refs.form.validateField("ownerId");
    },
    // 选择药材
    handDrugChange(item, index) {
      const { materials } = this.form.materialsItems[index];

      if (materials.findIndex(v => v.materialsId === item.id) !== -1) {
        this.$message.error(`${item.name} 已经添加过,请勿重复添加`)
        return
      }
      const g = this.unitList.find(v => v.unit === 'g');
      materials.push({
        materialsId: item.id, // 药材ID
        materialsName: item.name, // 药材名称
        dose: this.templateCategory === 1 ? 0.2 : 10, // 剂量
        unitId: g ? g.unitId : undefined, // 单位ID
      });

      this.form.materialsItems[index].materials = materials;
    },
    // 删除药材
    removeRow(pIndex, cIndex) {
      this.form.materialsItems[pIndex].materials.splice(cIndex, 1);
    },
    addForBox() {
      this.form.materialsItems.push({
        acupoints: [], // 穴位
        materials: [], // 药材
      })
    },
    removeForBox(index) {
      this.form.materialsItems.splice(index, 1);
    },
    // 打开穴位选择
    openAcupointSelect(index) {
      this.currentIndex = index;

      const ids = this.form.materialsItems[index].acupoints.map(v=> v.id);
      this.$refs.AcupointSelect.openModal(ids);
    },
    // 穴位选择确认
    acupointChange(nodes){
      this.form.materialsItems[this.currentIndex].acupoints = nodes.map(v=> {
        return {
          id: v.id,
          acupointName: v.label
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      const that = this;
      console.log(JSON.parse(JSON.stringify(that.form)));

      that.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            that.loading = true;
            that.form.prescriptionType = that.templateCategory + '';
            that.form.templateCategory = that.templateCategory;
            that.form.templateType = that.templateType;
            that.form.ownerType = that.templateType;
            if(that.form.regionCode){
              that.form.regionName = that.areaList.find(v => v.id === that.form.regionCode).name;
            }

            for (let i = 0; i < that.form.materialsItems.length; i++) {
              const { acupoints, materials } = that.form.materialsItems[i];
              const isApplication = that.form.prescriptionType == 1;
              if (acupoints.length === 0 && isApplication) {
                that.$message.error(`请在"贴${i + 1}"中添加穴位`);
                return false
              }else if(materials.length === 0){
                that.$message.error('请添加药材');
                return false
              }else{
                const noDose = materials.find(v=> !v.dose);
                if(noDose){
                  that.$message.error(`请${isApplication ? '在"贴' + (i + 1) + '"中' : ''}输入药材 (${noDose.materialsName}) 剂量`);
                  return false
                }
              }
            }

            if (that.form.templateId) {
              await updateTemplate(that.form);
            } else {
              await addTemplate(that.form);
            }
            that.$message.success(that.form.templateId ? "修改成功" : "新增成功");
            that.$emit("refresh");
            that.closeModal();
          } catch (error) {
            console.error('提交失败:', error);
            that.$message.error('提交失败，请重试');
          } finally {
            that.loading = false;
          }
        }
      })
    }
  },
}
</script>

<style lang="scss" scoped>
.formItemTitle {
  width: 110px;
  text-align: right;
  line-height: 36px;
  color: #606266;
  padding: 0 12px 0 0;
  box-sizing: border-box;
  font-weight: 700;
}

// 贴敷样式
.forBox {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 5px;
  overflow: hidden;
  margin-top: 10px;
  .formItemTitle {
    width: 80px;
  }
  .sortTag {
    position: relative;
    top: -10px;
    left: -10px;
  }
  .forTag{
    margin: 2px;
  }
}
</style>
